package cn.npe.domain.strategy.service.rule.impl;

import cn.npe.domain.strategy.model.RuleActionEntity;
import cn.npe.domain.strategy.model.RuleMatterEntity;
import cn.npe.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.npe.domain.strategy.repository.IStrategyRepository;
import cn.npe.domain.strategy.service.annotation.LogicStrategy;
import cn.npe.domain.strategy.service.rule.ILogicFilter;
import cn.npe.domain.strategy.service.rule.factory.DefaultLogicFactory;
import cn.npe.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.*;

/**
 * @author zhjx
 * @version 1.0.0
 * @ClassName RuleWeightLogicFilter.java
 * @Description 【抽奖前规则】根据抽奖权重返回可抽奖范围KEY
 * @createTime 2024/3/9 14:44
 */
@Slf4j
@Component
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.RULE_WIGHT)
public class RuleWeightLogicFilter implements ILogicFilter<RuleActionEntity.RaffleBeforeEntity> {

    @Resource
    private IStrategyRepository repository;

    public Long userScore = 4500L;
    @Override
    public RuleActionEntity<RuleActionEntity.RaffleBeforeEntity> filter(RuleMatterEntity ruleMatterEntity) {
        log.info("规则过滤-权重范围 userId:{} strategyId:{} ruleModel:{}", ruleMatterEntity.getUserId(), ruleMatterEntity.getStrategyId(), ruleMatterEntity.getRuleModel());
        String userId=ruleMatterEntity.getUserId();
        Long strategyId=ruleMatterEntity.getStrategyId();

        String ruleValue=repository.queryStrategyRuleValue(ruleMatterEntity.getStrategyId(),ruleMatterEntity.getAwardId(),ruleMatterEntity.getRuleModel());
        //1、根据用户Id查询抽奖用户的积分值 本章先使用固定值
        //获取
         Map<Long,String> analyticalValueGroup=getAnalyticalValue(ruleValue);
         if(null==analyticalValueGroup||analyticalValueGroup.isEmpty()){
             return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder().code(RuleLogicCheckTypeVO.ALLOW.getCode())
                     .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                     .build();

         }
         //转换key值 并，默认排序
        List<Long> analyticaSortedKeys=new ArrayList<>(analyticalValueGroup.keySet());
        Collections.sort(analyticaSortedKeys);

        //找出最小符合的值也就是【4500 积分，能找到 4000:102,103,104,105】、【5000 积分，能找到 5000:102,103,104,105,106,107】
        Long nextValue=analyticaSortedKeys.stream().filter(key->userScore>=key).findFirst().orElse(null);
        //可以找出 抽奖策略由此处接管
        if(null!=nextValue){
            return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                    .data(RuleActionEntity.RaffleBeforeEntity.builder()
                            .strategyId(strategyId)
                            .ruleWeightValueKey(analyticalValueGroup.get(nextValue))
                            .build())
                    .ruleModel(DefaultLogicFactory.LogicModel.RULE_WIGHT.getCode())
                    .code(RuleLogicCheckTypeVO.TAKE_OVER.getCode()).info(RuleLogicCheckTypeVO.TAKE_OVER.getInfo()).build();
        }

        return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                .build();
    }

    private Map<Long, String> getAnalyticalValue(String ruleValue) {
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> ruleValueMap = new HashMap<>();
        for (String ruleValueKey : ruleValueGroups) {
            // 检查输入是否为空
            if (ruleValueKey == null || ruleValueKey.isEmpty()) {
                return ruleValueMap;
            }
            // 分割字符串以获取键和值
            String[] parts = ruleValueKey.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
            }
            ruleValueMap.put(Long.parseLong(parts[0]), ruleValueKey);
        }
        return ruleValueMap;
    }
}
